const dm = require("../core/DataManager");
const fs = require("fs-extra");

let icons = (() => {
    try {
        let jsondata = fs.readFileSync('public/icon/iconfont.json', "utf8");
        return JSON.parse(jsondata).glyphs || [];
    } catch (err) {
        NCUTCAT.error(`FileManager - 无法加载图标: ${err}`);
        return [];
    }
})();

let iconsMap = (() => {
    let map = {};
    icons.forEach(e => map[e.font_class] = e);
    return map;
})();

module.exports.icons = icons;
module.exports.iconsMap = iconsMap;

function fileChecker(type, buff) {
    // if (type === 'image') {
    //     buff = imagesTool(buff).encode("j1pg", { operation: 100 });
    //     return buff;
    // }
    return undefined;
}
/**
 * 加载用户上传数据
 * req.upload_info={"fn":fileName,"fs":fileSize,"ft":fileType,"f":file,"u":user,"err":err};
 */
async function loadPostFile(type, req, res, next) {
    let fs, ft, user, chunks = [];
    var back = (err) => {
        req.upload_info = { "fs": fs, "ft": ft, "f": chunks, "u": user, "err": err };
        return next();
    }

    fs = parseInt(req.headers['x-file-size']);
    ft = req.headers['x-file-type'];
    if (!(fs > 0)) return back("缺少参数");
    if (!ft.startsWith(type)) return back("文件类型不正确");
    else ft = ft.substring(type.length + 1);

    let uid = req.token_result.uid;
    let size = 0;
    dm.getUserByID(uid, (msg, u) => {
        if (msg || !u) {
            NCUTCAT.warning(msg, u);
            return back("用户不存在");
        } else user = u;
        if (fs > user.p_u_f_s_s) return back("文件过大");


        req.on('data', (chunk) => {
            chunks.push(chunk);
            size += chunk.length;
        });

        req.on('end', err => {
            if (err) return back(err);
            chunks = Buffer.concat(chunks, size);
            let str = chunks.toString();
            if (str.length != fs) return back("文件大小不正确");

            chunks = fileChecker(type, chunks) || chunks;
            back();
        });
    });
}

/**
获取加载上传文件的func
@param type 文件类型(filetype)
*/
module.exports.getLoadPostFileFunction = (type) => {
    return (req, res, next) => loadPostFile(type, req, res, next);
}

NCUTCAT.infoLog("FileManager", "成功加载");